﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using BarCode.Common;
using System.IO;
using BarCode.Module;
using BarCode.AccessDao;
using System.Runtime.InteropServices;
using BarCode.Bean;
using System.IO.Ports;
using System.Threading;

namespace BarCode.Forms
{
    public partial class JK_BarCode : Form
    {
        [DllImport("user32.dll")]
        public static extern bool MessageBeep(uint uType);

        private static readonly log4net.ILog LogUtil = log4net.LogManager.GetLogger(typeof(JK_BarCode));


        // 机壳查找检查
        private bool jkSearch = true;

        private SerialPort ComDevice = new SerialPort(); // 监视器串口
        private string stationNo = "";  // 工作区号
        private int workAmount = 0; // 工作量
        private int valveStopWait = 3;

        public JK_BarCode()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Base_BarCode_Load(object sender, EventArgs e)
        {

            // 读取机壳查找设置
            string jkSearchVal = IniFileHelper.ReadValue("JXJK", "JK_Search_Enable");
            if (!"1".Equals(jkSearchVal) && !String.IsNullOrEmpty(jkSearchVal))
            {
                jkSearch = false;
            }
            
            lblUser.Text = GlobalVal.CurrentUser.User;
            lblStatus.Text = "当前为正常工作状态！";
            txtJKCode.Focus();
            if (GlobalVal.bolNetConnect)
            {
                btnNet.Enabled = false;
            }
            else
            {
                btnNet.Enabled = true;
            }

            // 工位号获取
            stationNo = IniFileHelper.getStringValue("System", "Work_Station");
            if (string.IsNullOrEmpty(stationNo))
            {
                MessageUtil.Error("工位号未设置，请设置后重启程序。");
                Application.Exit();
            }

            // 加载监视器
            bool loadRet = ComUtil.LoadMonitor(ComDevice);
            if (!loadRet)
            {
                MessageUtil.Error("监视器无法连接，请设置正确串口后重启程序。");
                Application.Exit();
            }

            // 停阀指令等待时间
            valveStopWait = IniFileHelper.getIntegerValue("JK", "VALVE_STOP_WAIT", 3);

            // 获取当前用户当天的工作量
            if (GlobalVal.bolNetConnect)
            {
                DB01Dao db01 = new DB01Dao(GlobalVal.ipAddressInfo.SERVICE_IP, GlobalVal.serverMysqlInfo.USERID, GlobalVal.serverMysqlInfo.USERPWD);
                int workAmount = db01.getJKWorkAmount(GlobalVal.CurrentUser.User);
                lblAmount.Text = (workAmount + GlobalVal.offSetInfo.jkoffset).ToString();
            }
            else
            {
                BarCodeMdbDao barcodeMdbDao = new BarCodeMdbDao();
                int workAmount = barcodeMdbDao.getJKWorkAmount(GlobalVal.CurrentUser.User);
                lblAmount.Text = (workAmount + GlobalVal.offSetInfo.jkoffset).ToString();
                barcodeMdbDao.Release();
            }

            GlobalVal.jkCountI_OK = Convert.ToInt32(lblAmount.Text);
            txtJKCode.Text = "";
            txtJKCode.Focus();
        }

        /// <summary>
        /// 窗体关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Base_BarCode_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (GlobalVal.bolNetConnect)
            {
                GlobalVal.bolUploadSubMain = false;
                modeFunction.upload_Data("jk");
            }
            Application.Exit();
        }

       
        /// <summary>
        /// 联通网络 按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNet_Click(object sender, EventArgs e)
        {
            DB01Dao db01 = new DB01Dao(GlobalVal.ipAddressInfo.SERVICE_IP, GlobalVal.serverMysqlInfo.USERID, GlobalVal.serverMysqlInfo.USERPWD);
            if (db01.EnableConnect() && Consts.CONNECT_SUCCESS.Equals(db01.getConnetText()))
            {
                GlobalVal.bolNetConnect = true;
                btnNet.Enabled = false;
            }
            else
            {
                GlobalVal.bolNetConnect = false;
                btnNet.Enabled = true;
            }
        }

        /// <summary>
        /// 二维码输入后回车事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtBarCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            lblStatus.Text = "";
            lblAmount.BackColor = Color.Transparent;
            if (e.KeyChar == (char)13)
            {
                string inputBarCode = txtJKCode.Text;
                //// 条码长度检查
                //if (inputBarCode.Length < 11 || inputBarCode.Length > 12)
                //{
                //    ShowInputWarn("条码信息不足！",Consts.MB_ICONASTERISK);
                //    return;
                //}

                // 条码长度检查
                if (inputBarCode.Length < 11 || inputBarCode.Length > 14)
                {
                    ShowInputWarn("条码信息位数不正确！", Consts.MB_ICONASTERISK);
                    sendFail();
                    return;
                }


                //// 11位时检查
                //if (inputBarCode.Length == 11)
                //{
                //    if (inputBarCode.StartsWith("91"))
                //    {
                //        inputBarCode = "901" + inputBarCode.Substring(2);
                //        txtJKCode.Text = inputBarCode;
                //    }
                //    else
                //    {
                //        ShowInputWarn("无效条码信息不能扫描！", Consts.MB_ICONASTERISK);
                //        return;
                //    }                    
                //} 
                //else if (!inputBarCode.StartsWith("9"))
                //{
                //    // 如果不是9开头的条码视为无效
                //    ShowInputWarn("无效条码信息不能扫描！", Consts.MB_ICONASTERISK);
                //    return;
                //}
                if (!inputBarCode.StartsWith("9"))
                {
                    // 如果不是9开头的条码视为无效
                    ShowInputWarn("无效条码信息不能扫描！", Consts.MB_ICONASTERISK);
                    sendFail();
                    return;
                }

                string jxCode = "";
                if (jkSearch)
                {
                    DB01Dao db01 = new DB01Dao(GlobalVal.ipAddressInfo.SERVICE_IP, GlobalVal.serverMysqlInfo.USERID, GlobalVal.serverMysqlInfo.USERPWD);
                    if (!db01.EnableConnect())
                    {
                        ShowInputWarn("服务器Mysql数据库无法访问！", Consts.MB_ICONASTERISK);
                        sendFail();
                        return;
                    }
                    jxCode = db01.getJXCodeByJk(inputBarCode);
                }
                else
                {
                    JXJKDBDao dbJxJk = new JXJKDBDao(GlobalVal.ipAddressInfo.JXJK_IP, GlobalVal.ipAddressInfo.JXJK_DBNAME, GlobalVal.JXJKMySQLInfo.USERID, GlobalVal.JXJKMySQLInfo.USERPWD);
                    if (!dbJxJk.EnableConnect())
                    {
                        ShowInputWarn("本地Mysql数据库无法访问！", Consts.MB_ICONASTERISK);
                        sendFail();
                        return;
                    }
                    jxCode = dbJxJk.getJXCodeByJK(inputBarCode);
                }

                if (String.IsNullOrEmpty(jxCode))
                {
                    LogUtil.Error("该机壳信息不存在！ -- " + inputBarCode);
                    ShowInputWarn("该机壳信息不存在！", Consts.MB_ICONASTERISK);
                    lblAmount.BackColor = Color.Red;
                    sendFail();
                    return;
                }
                else
                {
                    txtJXCode.Text = jxCode;
                    JKBarCodeInfo jkBarInfo = new JKBarCodeInfo();
                    jkBarInfo.JkBarcodeId = inputBarCode;
                    jkBarInfo.OperatorName = GlobalVal.CurrentUser.User;
                    jkBarInfo.OpDt = DateTime.Now;

                    BarCodeMdbDao barcodeMdbDao = new BarCodeMdbDao();
                    int delCnt = barcodeMdbDao.deleteJKBarCode(jkBarInfo);
                    int insCnt = barcodeMdbDao.insertJKBarCode(jkBarInfo);
                    if (delCnt == 0)
                    {
                        // 新追加
                        GlobalVal.jkCountI_OK = GlobalVal.jkCountI_OK + 1;
                    }

                    lblStatus.Text = "";
                    if (GlobalVal.bolNetConnect)
                    {
                        // 上传数据
                        GlobalVal.bolUploadSubMain = false;
                        modeFunction.upload_Data("jk");
                    }

                    // 获取当前用户当天的工作量
                    if (GlobalVal.bolNetConnect)
                    {
                        // 获取偏移量信息
                        DB01Dao db01 = new DB01Dao(GlobalVal.ipAddressInfo.SERVICE_IP, GlobalVal.serverMysqlInfo.USERID, GlobalVal.serverMysqlInfo.USERPWD);
                        GlobalVal.offSetInfo.jkoffset = db01.getOffSetValue(Consts.WORK_POSITION_JK);
                        lblAmount.Text = (GlobalVal.jkCountI_OK + GlobalVal.offSetInfo.jkoffset).ToString();
                    }
                    
                    // 清空输入内容
                    txtJKCode.Text = "";
                    txtJKCode.Focus();

                    sendSuccess();
                    
                }
                      
            }

        }

        /// <summary>
        /// 输入有误时弹框显示
        /// </summary>
        /// <param name="msg"></param>
        private void ShowInputWarn(string msg, uint beep)
        {
            txtJKCode.Text = "";
            txtJKCode.Focus();
            txtJXCode.Text = "";
            lblStatus.Text = msg;
            if (beep > 0)
            {
                MessageBeep(beep);
            }
        }


        private bool LoadMonitor(string portName)
        {
            ComDevice.PortName = portName;
            ComDevice.BaudRate = 9600;
            ComDevice.Parity = Parity.Even;
            ComDevice.DataBits = 8;
            ComDevice.StopBits = StopBits.One;
            try
            {
                ComDevice.Open();
                return true;
            }
            catch (Exception ex)
            {
                lblStatus.Text = ex.Message;
                LogUtil.Error("串口打开异常", ex);
                return false;
            }

        }

        /// <summary>
        /// 发送成功指令
        /// </summary>
        /// <param name="workAmount"></param>
        private void sendSuccess()
        {
            try
            {
                workAmount = GlobalVal.jkCountI_OK + GlobalVal.offSetInfo.jkoffset;
                string sendCode = ComUtil.createSuccessCodeWithCloseValve(stationNo, workAmount);
                bool sendRet = false;
                int sendCnt = 0;
                do
                {
                    Application.DoEvents();
                    sendRet = ComUtil.sendData(ComDevice, sendCode);
                    Application.DoEvents();
                    sendCnt++;

                } while (!sendRet && sendCnt < 3);

                // 1秒后发送停止警报命令
                for (int i = 0; i < valveStopWait*10; i++)
                {
                    Application.DoEvents();
                    Thread.Sleep(100);
                }
                sendCloseValve();

            }
            catch (Exception ex)
            {
                LogUtil.Error("发送成功指令异常发生", ex);
            }
        }

        /// <summary>
        /// 发送失败指令
        /// </summary>
        /// <param name="workAmount"></param>
        private void sendFail()
        {
            try
            {
                workAmount = GlobalVal.jkCountI_OK + GlobalVal.offSetInfo.jkoffset;
                string sendCode = ComUtil.createFailCode(stationNo, workAmount);
                bool sendRet = false;
                int sendCnt = 0;
                do
                {
                    Application.DoEvents();
                    sendRet = ComUtil.sendData(ComDevice, sendCode);
                    Application.DoEvents();
                    sendCnt++;

                } while (!sendRet && sendCnt < 3);

                // 1秒后发送停止警报命令
                Thread.Sleep(1000);
                sendStopWarn();
            }
            catch (Exception ex)
            {
                LogUtil.Error("发送失败指令异常发生", ex);
            }
        }

        /// <summary>
        /// 发送停鸣指令
        /// </summary>
        private void sendStopWarn()
        {
            try
            {
                workAmount = GlobalVal.jkCountI_OK + GlobalVal.offSetInfo.jkoffset;
                string sendCode = ComUtil.createStopWarnCode(stationNo, workAmount);
                bool sendRet = false;
                int sendCnt = 0;
                do
                {
                    Application.DoEvents();
                    sendRet = ComUtil.sendData(ComDevice, sendCode);
                    Application.DoEvents();
                    sendCnt++;

                } while (!sendRet && sendCnt < 3);
            }
            catch (Exception ex)
            {
                LogUtil.Error("发送停鸣指令异常发生", ex);
            }
        }

        /// <summary>
        /// 发送关阀指令
        /// </summary>
        private void sendCloseValve()
        {
            try
            {
                workAmount = GlobalVal.jkCountI_OK + GlobalVal.offSetInfo.jkoffset;
                string sendCode = ComUtil.createCloseValveCode(stationNo, workAmount);
                bool sendRet = false;
                int sendCnt = 0;
                do
                {
                    Application.DoEvents();
                    sendRet = ComUtil.sendData(ComDevice, sendCode);
                    Application.DoEvents();
                    sendCnt++;

                } while (!sendRet && sendCnt < 3);
            }
            catch (Exception ex)
            {
                LogUtil.Error("发送关阀指令异常发生", ex);
            }
        }


        /// <summary>
        /// 发送输入中指令
        /// </summary>
        /// <param name="workAmount"></param>
        private void sendInputing()
        {
            try
            {
                workAmount = GlobalVal.jkCountI_OK + GlobalVal.offSetInfo.jkoffset;
                string sendCode = ComUtil.createInputingCode(stationNo, workAmount);
                bool sendRet = false;
                int sendCnt = 0;
                do
                {
                    Application.DoEvents();
                    sendRet = ComUtil.sendData(ComDevice, sendCode);
                    Application.DoEvents();
                    sendCnt++;

                } while (!sendRet && sendCnt < 3);

            }
            catch (Exception ex)
            {
                LogUtil.Error("发送输入中指令异常发生", ex);
            }
        }
    }
}
